﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
using Sunny.UI;

namespace SmartMotion.Core
{
    public class Json
    {
        public static T Load<T>(string fileName)
        {
            try
            {
                object obj = null;
                if (File.Exists(fileName))
                {
                    string str = File.ReadAllText(fileName);
                    obj = JsonConvert.DeserializeObject<T>(str, new JsonSerializerSettings
                    {
                        NullValueHandling = NullValueHandling.Ignore,
                    });
                }
                return (T)obj;
            }
            catch (Exception ex)
            {
                UIMessageBox.ShowError($"加载Json时发现错误的工具,返回一个Null对象\r{ex.Message}\r{ex.StackTrace}");
                return default(T);
            }
        }

        public static T LoadExt<T>(string fileName)
        {
            try
            {
                object obj = null;
                if (File.Exists(fileName))
                {
                    string str = File.ReadAllText(fileName);
                    obj = JsonConvert.DeserializeObject<T>(str, new JsonSerializerSettings() { TypeNameHandling = TypeNameHandling.All });
                }
                return (T)obj;
            }
            catch (Exception ex)
            {
                UIMessageBox.ShowError($"加载Json时发现错误的工具,返回一个Null对象\r{ex.Message}\r{ex.StackTrace}");
                return default(T);
            }
        }

        //-----------------------------------------------------------------------------------------------------
        /// <summary>
        /// 保存配置
        /// </summary>
        /// <param name="fileName"></param>
        /// <returns></returns>
        public static bool Save<T>(string fileName, object obj)
        {
            string str = JsonConvert.SerializeObject(obj);
            File.WriteAllText(fileName, str);
            return true;
        }

        //-----------------------------------------------------------------------------------------------------
        /// <summary>
        /// 保存配置
        /// </summary>
        /// <param name="fileName"></param>
        /// <returns></returns>
        public static bool SaveExt<T>(string fileName, object obj)
        {
            string str = JsonConvert.SerializeObject(obj, new JsonSerializerSettings() { TypeNameHandling = TypeNameHandling.All });
            File.WriteAllText(fileName, str);
            return true;
        }

    }

}
